package com.wechat.backend.controller;

import com.wechat.backend.entity.Friend;
import com.wechat.backend.entity.User;
import com.wechat.backend.repository.FriendRepository;
import com.wechat.backend.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/friend")
public class FriendController {

    @Autowired
    private FriendService friendService;

    @Autowired
    private FriendRepository friendRepository;

    //获取好友列表
    @GetMapping("/list")
    public List<User> getFriends(@RequestParam Integer userId) {
        return friendService.getFriends(userId);
    }

    // 添加好友
    // @PostMapping("/add")
    // public Map<String, Object> addFriend(@RequestBody Map<String, Integer> req) {
    //     Integer userId = req.get("userId");
    //     Integer friendId = req.get("friendId");
    //     boolean ok = friendService.addFriend(userId, friendId);
    //     Map<String, Object> result = new HashMap<>();
    //     result.put("success", ok);
    //     result.put("message", ok ? "添加成功" : "添加失败");
    //     return result;
    // }

    @PostMapping("/request")
    public Map<String, Object> addFriendRequest(@RequestBody Map<String, Integer> req) {
        Integer userId = req.get("userId");
        Integer friendId = req.get("friendId");
        // 检查是否已存在
        Friend exist = friendRepository.findByUserIdAndFriendId(userId, friendId);
        Map<String, Object> result = new HashMap<>();
        if (exist != null) {
            result.put("success", false);
            result.put("message", "已发送过请求或已是好友");
            return result;
        }
        Friend f = new Friend();
        f.setUserId(userId);
        f.setFriendId(friendId);
        f.setStatus("pending");
        friendRepository.save(f);
        result.put("success", true);
        result.put("message", "好友请求已发送");
        return result;
    }

    // 查询我收到的好友请求
    @GetMapping("/requests/received")
    public List<Friend> getReceivedRequests(@RequestParam Integer userId) {
        return friendService.getReceivedRequests(userId);
    }

    // 查询我发出的好友请求
    @GetMapping("/requests/sent")
    public List<Friend> getSentRequests(@RequestParam Integer userId) {
        return friendService.getSentRequests(userId);
    }

    // 同意好友请求
    @PostMapping("/requests/accept")
    public Map<String, Object> acceptRequest(@RequestBody Map<String, Integer> req) {
        return friendService.acceptRequest(req.get("requestId"));
    }

    // 拒绝好友请求
    @PostMapping("/requests/reject")
    public Map<String, Object> rejectRequest(@RequestBody Map<String, Integer> req) {
        return friendService.rejectRequest(req.get("requestId"));
    }
} 